const fs = require('fs');
const path = require('path');
const UglifyJS = require('uglify-js');

// 复制文件夹及其内容
const copyFolderSync = (from, to) => {
    fs.mkdirSync(to, { recursive: true });
    fs.readdirSync(from).forEach(element => {
        if (fs.lstatSync(path.join(from, element)).isFile()) {
            fs.copyFileSync(path.join(from, element), path.join(to, element));
        } else {
            copyFolderSync(path.join(from, element), path.join(to, element));
        }
    });
};

// 删除文件夹及其内容
const deleteFolderRecursive = function (directoryPath) {
    if (fs.existsSync(directoryPath)) {
        fs.readdirSync(directoryPath).forEach(function (file) {
            const curPath = path.join(directoryPath, file);
            if (fs.lstatSync(curPath).isDirectory()) {
                deleteFolderRecursive(curPath);
            } else {
                fs.unlinkSync(curPath);
            }
        });
        fs.rmdirSync(directoryPath);
    }
};

// 获取当前时间作为版本号
const getVersion = () => {
    const now = new Date();
    return now.getFullYear().toString().slice(-2) +
        ('0' + (now.getMonth() + 1)).slice(-2) +
        ('0' + now.getDate()).slice(-2) +
        ('0' + now.getHours()).slice(-2) +
        ('0' + now.getMinutes()).slice(-2) +
        ('0' + now.getSeconds()).slice(-2);
};



// TODO: 修改目录
const sourceDir = 'pages';
const distDir = 'dist';

// 删除旧的 dist 目录
console.log('正在删除旧的 dist 目录...');
deleteFolderRecursive(distDir);
console.log('旧的 dist 目录删除成功。');

// 复制 pages 目录到 dist 目录
console.log('正在复制 pages 目录到 dist 目录...');
copyFolderSync(sourceDir, distDir);
console.log('pages 目录成功复制到 dist 目录。');



// 获取当前时间的字符串表示，例如：20240326-125959
function getCurrentTimestamp() {
    const now = new Date();
    const year = now.getFullYear();
    const month = (now.getMonth() + 1).toString().padStart(2, '0');
    const day = now.getDate().toString().padStart(2, '0');
    const hours = now.getHours().toString().padStart(2, '0');
    const minutes = now.getMinutes().toString().padStart(2, '0');
    const seconds = now.getSeconds().toString().padStart(2, '0');
    return `${year}${month}${day}-${hours}${minutes}${seconds}`;
}
const timestamp = getCurrentTimestamp();
  
// 压缩指定文件，并写入新文件
function compressAndWriteFile(directory, fileName) {
    const filePath = path.join(directory, fileName);
    const fileContent = fs.readFileSync(filePath, 'utf8');
    const minifiedCode = UglifyJS.minify(fileContent).code;
    const compressedFileName = `${fileName}-v${timestamp}.min.js`;
    const compressedFilePath = path.join(directory, compressedFileName);
    fs.writeFileSync(compressedFilePath, minifiedCode, 'utf8');
    console.log(`文件已压缩: ${filePath} => ${compressedFilePath}`);
    // 删除原文件
    fs.unlinkSync(filePath);
    console.log(`原文件已删除: ${filePath}`);
}
  
  // 压缩指定目录下的文件
  function compressFilesInDirectory(directory, targetFiles) {
    console.log(`扫描目录: ${directory}`);
    fs.readdirSync(directory).forEach((file) => {
      if (targetFiles.includes(file)) {
        console.log(`找到目标文件: ${file}`);
        compressAndWriteFile(directory, file);
      }
    });
  }
  
  // 执行压缩
  function compressSpecifiedFiles(oldJsDirectories, oldJsFileNames) {
    const directories = oldJsDirectories; // 指定需要压缩的目录
    const targetFiles = oldJsFileNames; // 指定需要压缩的文件名
    console.log('开始压缩...');
    directories.forEach((directory) => {
      compressFilesInDirectory(directory, targetFiles);
    });
    console.log('压缩完成.');
  }

// TODO: 修改压缩的目录，修改压缩的JS文件名
// 旧的 JS 文件名数组
const oldJsDirectories = ['dist/js']; // 指定需要压缩的目录
const oldJsFileNames = ['index.js']; // 指定需要压缩的文件名
// 新的压缩后的 JS 文件名数组
const suffix = `-v${timestamp}.min.js`;
var newJsFileNames = [];
oldJsFileNames.forEach(oldFileName => {
    const baseName = oldFileName.split('.')[0]; // 获取没有扩展名的基本名称
    const newFileName = baseName + suffix;
    newJsFileNames.push(newFileName);
});
// 执行压缩
compressSpecifiedFiles(oldJsDirectories, oldJsFileNames);


// 遍历目录下的所有文件和子目录
const traverseDirectory = (directoryPath) => {
    const files = fs.readdirSync(directoryPath);
    files.forEach(file => {
        const filePath = path.join(directoryPath, file);
        const stats = fs.statSync(filePath);
        if (stats.isDirectory()) {
            // console.log(`${file} 是一个目录`);
            // 递归遍历子目录
            traverseDirectory(filePath);
        } else {
            if (file.endsWith('.html')) {
                console.log(`${file} 是一个文件`);
                let htmlContent = fs.readFileSync(filePath, 'utf-8');
                // 替换 HTML 内容中的引用
                oldJsFileNames.forEach((oldJsFileName, index) => {
                    htmlContent = htmlContent.replace(oldJsFileName, newJsFileNames[index]);
                });
                // 将替换后的内容写回 HTML 文件
                fs.writeFileSync(filePath, htmlContent, 'utf-8');
                console.log(`${file} 文件中的 JS 引用已替换完成。`);
            }
        }
    });
};
// 调用函数开始遍历
traverseDirectory(distDir);
